  <template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加分类按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addClassify">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <tree-table
        :data="storeCommodityCate"
        :columns="columns"
        :selection-type="false"
        border
        :show-row-hover="false"
        show-index
        index-text="#"
        :expand-type="false"
        class="treeTable"
      >
        <!-- 是否有效模板 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color:lightgreen;"
          ></i>
          <i class="el-icon-error" v-else style="color:red;"></i>
        </template>
        <!-- 排序模版 -->
        <template slot="sort" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作模板 -->
        <template slot="operation" slot-scope="scope">
          <el-button size="mini" icon="el-icon-edit" type="primary" @click="compileClick(scope.row.cat_id)">编辑</el-button>
          <el-button size="mini" icon="el-icon-delete" type="danger" @click="delClick(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="querInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 分类按钮弹框 -->
     <el-dialog title="提示" :visible.sync="classifyVisible" width="50%" @close="addCateDialogClosed">
      <!-- 主体表单区域 -->
      <el-form
        :model="addClassifyList"
        :rules="addClassifyRules"
        ref="addClassifyRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addClassifyList.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- 级联选择器 -->
          <!-- options 用来指定数据源 -->
          <!-- props 用来指定配置对象 -->
          <el-cascader v-model="seletedKeys" :options="obtainClassifyList"
           :props="cascaderProps" :popper-append-to-body="false" clearable
            change-on-select @change="parentCateChange"></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="classifyVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑按钮弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="compileVisible" @close="compileDialogClosed"
      width="30%">
      <el-form :model="compileForm" :rules="addClassifyRules" ref="compileRef" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="compileForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="compileVisible = false">取 消</el-button>
        <el-button type="primary" @click="compile">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 查询条件
      querInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 存储商品分类
      storeCommodityCate: [],
      // 商品总数量
      total: 0,
      // 为表格指定列的数据
      columns: [
        { label: '分类名称', prop: 'cat_name' },
        // type:自定义为模板列 template:表示使用的当前模板名称
        { label: '是否有效', type: 'template', template: 'isok' },
        { label: '排序', type: 'template', template: 'sort' },
        { label: '操作', type: 'template', template: 'operation' }
      ],
      // 添加分类弹框显示隐藏
      classifyVisible: false,
      // 添加商品分类数据
      addClassifyList: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      // 添加分类校验规则
      addClassifyRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 获取数据库商品分类
      obtainClassifyList: [],
      // 级联选择器双向绑定
      seletedKeys: [],
      // 用来指定配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 编辑按钮弹框显示隐藏
      compileVisible: false,
      // 编辑表单数据
      compileForm: {}
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: this.querInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      }
      this.storeCommodityCate = res.data.result
      this.total = res.data.total
    },
    // 监听一页显示条数
    handleSizeChange (newSize) {
      this.querInfo.pagesize = newSize
      this.getCateList()
    },
    // 监听页码变化
    handleCurrentChange (newPage) {
      this.querInfo.pagenum = newPage
      this.getCateList()
    },
    // 添加分类按钮点击事件
    addClassify () {
      this.getObtainClassify()
      this.classifyVisible = true
    },
    // 获取一二级商品分类
    async getObtainClassify () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.obtainClassifyList = res.data
      console.log(this.obtainClassifyList)
    },
    // 级联选择器发生变化触发
    parentCateChange () {
      // 如果级联选择器双向绑定长度大于0则选的的不是父级分类
      if (this.seletedKeys.length > 0) {
        // 父级id
        this.addClassifyList.cat_pid = this.seletedKeys[this.seletedKeys.length - 1]
        // 当前分类等级赋值
        this.addClassifyList.cat_level = this.seletedKeys.length
      } else {
        this.addClassifyList.cat_pid = 0
        this.addClassifyList.cat_level = 0
      }
    },
    // 添加分类
    addCate () {
      this.$refs.addClassifyRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.post('categories', this.addClassifyList)
        if (res.meta.status !== 201) {
          return this.$message.error('创建分类失败')
        }
        this.$message.success('创建分类成功')
        this.classifyVisible = false
        this.getCateList()
      })
    },
    // 添加分类 监听对话框的关闭事件，重置表单数据
    addCateDialogClosed () {
      this.$refs.addClassifyRef.resetFields()
      this.seletedKeys = []
      this.addClassifyList.cat_level = 0
      this.addClassifyList.cat_pid = 0
    },
    // 编辑按钮事件
    async compileClick (id) {
      this.compileVisible = true
      const { data: res } = await this.$http.get('categories/' + id)
      this.compileForm = res.data
    },
    // 编辑 监听对话框的关闭事件，重置表单数据
    compileDialogClosed () {
      this.$refs.compileRef.resetFields()
    },
    // 提交编辑
    compile () {
      this.$refs.compileRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.put('categories/' + this.compileForm.cat_id, {
          cat_name: this.compileForm.cat_name
        })
        if (res.meta.status !== 200) {
          return this.$message.error('编辑失败')
        }
        this.$message.success('编辑成功')
        this.compileVisible = false
        this.getCateList()
      })
    },
    // 删除事件
    async delClick (id) {
      const confirmMessage = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirmMessage !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getCateList()
    }
  }
}
</script>

<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>
